import { action, computed, makeObservable, observable } from 'mobx'
class AppleStore {
    apples = [
        {
            // 苹果id
            id: 0,
            // 重量
            weight: 10,
            // 是否被吃掉
            isEaten: false
        },
        {
            // 苹果id
            id: 1,
            // 重量
            weight: 10,
            // 是否被吃掉
            isEaten: false
        },
        {
            // 苹果id
            id: 2,
            // 重量
            weight: 10,
            // 是否被吃掉
            isEaten: false
        }
    ]

    // 开始采摘下标
    startId = 3
    // 是否正在采摘中
    isPicking = false

    constructor() {
        makeObservable(this, {
            apples: observable,
            isPicking: observable,
            eatApple: action,
            showApple: computed
        })
    }

    eatApple (id) {
        this.apples.forEach(apple => {
            if ( apple.id !== id ) return
            apple.isEaten = true
        })
    }

    getAnApple () {
        // 如果正在采摘中则直接结束不采摘苹果
        if (this.isPicking) return
        // 更改状态为正在采摘中
        this.isPicking = true
        
        getApple().then(res => {
            res.id = this.startId ++
            this.apples.push(res)
            this.isPicking = false
        })
    }

    get showApple () {
        return this.apples.filter(apple => !apple.isEaten)
    }

    get status () {
        let status = {
            appleNow: {
                quantity: 0,
                weight: 0
            },
            appleEaten: {
                quantity: 0,
                weight: 0
            }
        }
        this.apples.forEach(apple => {
            if (apple.isEaten) {
                status.appleEaten.quantity ++
                status.appleEaten.weight += apple.weight
            } else {
                status.appleNow.quantity ++
                status.appleNow.weight += apple.weight
            }
        })
        
        return status
    }
}

// 模拟异步采摘
function getApple() {
    let weight = Math.floor(200 + Math.random() * 50);
    let apple = {
        // 重量
        weight: weight,
        // 是否被吃掉
        isEaten: false
    }
    return new Promise(reslove => {
        setTimeout(() => {
            reslove(apple)
        }, 2000);
    })
}

export default AppleStore